package com.pharmacy.controller;


import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.pharmacy.dto.AddOrdersDto;
import com.pharmacy.dto.EasyPayDto;
import com.pharmacy.entity.Orders;
import com.pharmacy.result.Result;
import com.pharmacy.service.OrdersService;
import com.pharmacy.websocket.WebSocketServer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

@RestController
@RequestMapping("/admin/alipay")
@Slf4j
@Tag(name = "支付接口")
@CrossOrigin
public class EasyPayController {

    @Autowired
    private Config config;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private OrdersService ordersService;

    @Operation(summary = "调用aliyun支付接口")
    @PostMapping("/pay")
    public Result<String> pay(@RequestBody EasyPayDto easyPayDto) throws Exception {

        String price = easyPayDto.getPrice().toString();

        String paymentCode = UUID.randomUUID().toString(); // 生成唯一的支付码
        String payImg = paymentCode + ".png"; // 使用 ".png" 扩展名生成文件名
        String paymentImage = "C:\\Users\\Suaiqibin\\Desktop\\study\\pyarmacy\\src\\assets\\" + payImg; // 拼接文件路径和文件名

        Factory.setOptions(config);
        //调用支付接口
        AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate("妙妙药店", paymentCode, price);
        //解析结果
        log.info("respones", response);
        String httpBody = response.getHttpBody();

        //转json对象
        JSONObject jsonObject = JSONObject.parseObject(httpBody);
        String qrUrl = jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();
        //生成二维码
        try {
            QrCodeUtil.generate(qrUrl, 300, 300, new File(paymentImage));
        } catch (Exception e) {
            log.error("Error generating QR code: {}", e.getMessage());
        }

        return Result.success(payImg);
    }

    @Operation(summary = "接受成功信息")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        log.info("支付成功通知");
        String out_trade_no = request.getParameter("out_trade_no");
        String buyer_id = request.getParameter("buyer_id"); // 尝试获取买家 ID
        log.info("订单号：{}", out_trade_no);
        log.info("买家 ID：{}", buyer_id); // 记录买家 ID
        AddOrdersDto orders = new AddOrdersDto();
        orders.setOrderNumber(out_trade_no);
        orders.setBuyerId(buyer_id);
        ordersService.addOrders(orders);

        webSocketServer.sendToAllClient(out_trade_no);
        return "success";
    }


    @GetMapping("/query")
    public String query() throws Exception {
        Factory.setOptions(config);
        AlipayTradeQueryResponse response = Factory.Payment.Common().query("123456789");
        return response.getHttpBody();
    }

}
